/*
 * @Date         : 2022-03-03 16:12:40
 * @LastEditors  : zu1662
 * @LastEditTime : 2022-03-03 19:03:44
 * @Description  : 多语言 Hook
 * 
 * Copyright © 2022 by zu1662, All Rights Reserved. 
 */

import { useCallback } from "react"
import { LocaleType } from "@/types/app"
import { useStore } from "@/store"

/**
 * @description: 多语言切换 Hook 封装。因为使用了 Store 内数据，使用的组件内需要进行 observer
 * @param {*} 
 * @return {*} [locale, updateLocale]
 */
const useLocale = (): [LocaleType, (targetLocale?: LocaleType) => void] => {
  const { appStore } = useStore()
  const { locale, changeLocale } = appStore

  // 如果不存在值，则默认切换 语言
  const updateLocale = useCallback((targetLocale?: LocaleType) => {
    if(!targetLocale) {
      targetLocale = locale === 'zh' ? 'en' : 'zh'
    }
    changeLocale(targetLocale)
  }, [changeLocale, locale])

  return [locale, updateLocale]
}

export default useLocale